<template>
  <div class="chat-toggle-container">
    <!-- 悬浮小球 -->
    <div
      class="chat-toggle-btn"
      :class="{ 'expanded': isExpanded }"
      @click="toggleExpanded"
    >
      <el-icon v-if="!isExpanded"><ChatDotRound /></el-icon>
      <el-icon v-else><Close /></el-icon>
    </div>

    <!-- 展开后的搜索框 -->
    <div
      v-if="isExpanded"
      class="chat-container"
      :class="{ 'mobile': isMobile }"
    >
      <!-- 问答结果界面 -->
      <div class="answer-container">
        <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message-item', message.type === 'question' ? 'question-item' : 'answer-item', 'animate-fade-in']"
          :style="{ animationDelay: `${index * 0.05}s` }"
        >
          <div class="message-avatar">
            <img
              :src="message.type === 'question' ? userAvatar : aiAvatar"
              alt="avatar"
              class="avatar-img"
            />
          </div>
          <div class="message-content">
            <template v-if="message.isLoading">
              <div class="loading-dots">
                <span class="dot"></span>
                <span class="dot"></span>
                <span class="dot"></span>
              </div>
            </template>
            <div v-else v-html="formatContent(message.content)"></div>
          </div>
        </div>
      </div>

      <!-- 输入框 -->
      <div class="input-container animate-fade-in" style="animation-delay: 0.3s">
        <div class="input-wrapper" :class="{ 'focused': isInputFocused }">
          <input
            v-model="question"
            placeholder="请输入你的问题..."
            @keyup.enter="submitQuestion"
            @focus="isInputFocused = true"
            @blur="isInputFocused = false"
            class="question-input"
            :disabled="isLoading"
          />
          <button
            @click="submitQuestion"
            class="submit-btn btn-hover"
            :disabled="!question.trim() || isLoading"
          >
            <span v-if="!isLoading">提问</span>
            <div v-else class="btn-loading">
              <span class="dot"></span>
              <span class="dot"></span>
              <span class="dot"></span>
            </div>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import { ChatDotRound, Close } from '@element-plus/icons-vue';

// 存储问答消息
const messages = ref<{
  type: 'question' | 'answer';
  content: string;
  isLoading?: boolean;
}[]>([]);
// 用户输入的问题
const question = ref('');
// 输入框聚焦状态
const isInputFocused = ref(false);
// 加载状态
const isLoading = ref(false);
// 展开状态
const isExpanded = ref(false);

// 头像资源
const userAvatar = require('@/assets/user-avatar.png'); // 可替换为实际用户头像路径
const aiAvatar = require('@/assets/ai-avatar.png');     // 可替换为实际AI头像路径

// 判断是否为手机端
const isMobile = computed(() => window.innerWidth <= 576);

// 格式化内容（处理换行）
const formatContent = (content: string) => {
  return content.replace(/\n/g, '<br>');
};

// 切换展开/收起状态
const toggleExpanded = () => {
  isExpanded.value = !isExpanded.value;
  if (isExpanded.value) {
    // 滚动到底部
    setTimeout(() => {
      const container = document.querySelector('.answer-container');
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    }, 100);
  }
};

// 提交问题
const submitQuestion = async () => {
  const questionText = question.value.trim();
  if (!questionText || isLoading.value) return;

  // 添加用户问题到消息列表
  messages.value.push({
    type: 'question',
    content: questionText,
  });
  question.value = '';

  // 添加AI加载消息
  const loadingMsgIndex = messages.value.length;
  messages.value.push({
    type: 'answer',
    content: '',
    isLoading: true,
  });
  isLoading.value = true;

  try {
    const response = await fetch('http://127.0.0.1:8081/ai/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ question: questionText }),
    });

    // 确保服务器返回的是一个可读流
    if (!response.body) throw new Error('Response stream not available.');

    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let fullAnswer = '';

    // 移除加载状态，开始显示内容
    messages.value[loadingMsgIndex] = {
      type: 'answer',
      content: '',
      isLoading: false,
    };

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      const chunk = decoder.decode(value, { stream: true });
      fullAnswer += chunk;
      // 实时更新答案
      messages.value[loadingMsgIndex].content = fullAnswer;
    }
  } catch (error) {
    console.error('请求AI接口出错:', error);
    // 更新错误信息
    messages.value[loadingMsgIndex] = {
      type: 'answer',
      content: '请求出错，请稍后重试。',
      isLoading: false,
    };
  } finally {
    isLoading.value = false;
    // 滚动到底部
    setTimeout(() => {
      const container = document.querySelector('.answer-container');
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    }, 100);
  }
};

// 监听窗口大小变化，判断是否为手机端
onMounted(() => {
  window.addEventListener('resize', () => {
    // 这里可以根据需要添加响应式逻辑
  });
});
</script>

<style scoped>
/* 悬浮小球容器 */
.chat-toggle-container {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 999;
}

/* 悬浮小球按钮 */
.chat-toggle-btn {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #409eff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.chat-toggle-btn.expanded {
  background-color: #f56c6c;
}

/* 展开后的聊天容器 */
.chat-container {
  position: fixed;
  bottom: 80px;
  right: 20px;
  width: 360px;
  max-height: 500px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  transition: all 0.3s;
}

/* 手机端样式调整 */
.chat-container.mobile {
  width: calc(100% - 40px);
  right: 20px;
  left: 20px;
}

/* 基础布局 */
.answer-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message-item {
  display: flex;
  gap: 10px;
  max-width: 85%;
  animation-fill-mode: both;
}

.question-item {
  margin-left: auto;
}

.answer-item {
  margin-right: auto;
}

/* 头像样式 */
.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.avatar-img:hover {
  transform: scale(1.05);
}

/* 消息内容 */
.message-content {
  padding: 12px 16px;
  border-radius: 10px;
  font-size: 13px;
  line-height: 1.6;
  word-break: break-word;
  max-width: calc(100% - 46px);
}

.question-item .message-content {
  background: #e6f7ff;
  color: #001529;
  border-top-right-radius: 4px;
}

.answer-item .message-content {
  background: #f5f7fa;
  color: #001529;
  border-top-left-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 输入区域 */
.input-container {
  padding: 12px 16px;
  border-top: 1px solid #e2e8f0;
}

.input-wrapper {
  position: relative;
  display: flex;
  gap: 8px;
}

.question-input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #e2e8f0;
  border-radius: 20px;
  font-size: 13px;
  outline: none;
  transition: all 0.2s;
}

.question-input:disabled {
  background: #f8fafc;
  cursor: not-allowed;
}

.focused .question-input {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

/* 按钮样式 */
.submit-btn {
  padding: 0 16px;
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.submit-btn:disabled {
  background: #f0f2f5;
  color: #c9cdd4;
  cursor: not-allowed;
}

.btn-hover:not(:disabled):hover {
  background: #69b1ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

/* 加载动画 */
.loading-dots {
  display: flex;
  gap: 4px;
  align-items: center;
  height: 20px;
}

.loading-dots .dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #94a3b8;
  animation: bounce 1.4s infinite ease-in-out both;
}

.loading-dots .dot:nth-child(2) {
  animation-delay: -0.3s;
}

.loading-dots .dot:nth-child(3) {
  animation-delay: -0.6s;
}

.btn-loading {
  display: flex;
  gap: 4px;
}

.btn-loading .dot {
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background: #fff;
  animation: bounce 1.4s infinite ease-in-out both;
}

.btn-loading .dot:nth-child(2) {
  animation-delay: -0.3s;
}

.btn-loading .dot:nth-child(3) {
  animation-delay: -0.6s;
}

/* 动画类 */
.animate-fade-in {
  animation: fadeIn 0.4s ease forwards;
  opacity: 0;
}

/* 动画关键帧 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 4px;
  height: 4px;
}

::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 2px;
}

::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 2px;
}

::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}
</style>